package com.xugou.controller;

import com.xugou.pojo.Dept;
import com.xugou.service.DeptService;
import com.xugou.service.EmpService;
import com.xugou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/dept")
public class DeptController {

    static int deptId;

    @Autowired
    @Qualifier("deptServiceImpl")
    private DeptService deptService;


    //获取所有部门员工信息
    @RequestMapping("/alldept")
    public String getAllDeptInfo(HttpServletRequest req) {

        List<Dept> allDeptEmpList = deptService.getAllDeptEmpList();
        if (allDeptEmpList != null) {
            req.setAttribute("deptlist", allDeptEmpList);
            return "dept_index";
        } else {
            return null;
        }

    }


    //新增部门
    @RequestMapping("/addDept")
    //model res相当于从前端像后端传送数据的容器
    public String addNewDept(Model model,HttpServletRequest res) {


        String msg = "";
    //"deptName"前端输入框的数据名
        String deptName = res.getParameter("deptName");

        boolean flag = deptService.addNewDept(deptName);
        if (flag) {
            return "redirect:/dept/allDeptList";
        } else {
            msg = "error";
            model.addAttribute(msg);
            return "redirect:/dept/allDept";
        }
    }

    //获取所有部门信息
    @RequestMapping("/allDeptList")
    public String getDeptList(HttpServletRequest res){
        List<Dept> allDeptList = deptService.getAllDeptList();
        res.setAttribute("allDeptList",allDeptList);  //第一个参数发送的字符串  第二个是后端的数据
        return "dept_info";
    }
//    删除部门
    @RequestMapping("/delDept/{deptId}")
    public String delDeptList(@PathVariable("deptId") int id){
        deptService.delDept(id);
        return "redirect:/dept/allDeptList";
    }

    //跳转到部门修改界面
    @RequestMapping("/toUpdateDept/{deptId}")
    public String toUpdateDept(@PathVariable("deptId")int id,Model model){
        deptId=id;
        Dept deptById = deptService.getDeptById(id);
        model.addAttribute("deptById", deptById);
        return "dept/updateDept";
    }

    //部门修改
    @RequestMapping("/updateDept")
    public String updateDept(String deptName){

        Dept dept = new Dept();
        dept.setDeptId(deptId);
        dept.setDeptName(deptName);

        int i = deptService.updateDept(dept);

        if(i==1){
            return "redirect:/dept/allDeptList";
        }else {
            return "dept/updateDept";
        }

    }


}
